package com.xgsm.springsecurityauthdemo.Service;

import com.xgsm.springsecurityauthdemo.domain.ResponseResult;
import com.xgsm.springsecurityauthdemo.domain.User;
import com.xgsm.springsecurityauthdemo.domain.UserLogin;
import com.xgsm.springsecurityauthdemo.utils.JwtUtil;
import com.xgsm.springsecurityauthdemo.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
//        3、使用ProviderManager auth方法进行验证
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
//        如果校验失败
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误，请重试");
        }
//        4、自己生成jwt给前端
        UserLogin userLogin = (UserLogin) (authenticate.getPrincipal());
        String userId = userLogin.getUser().getId().toString();
        String Jwt = JwtUtil.createJWT(userId);
        Map<String, String> map = new HashMap<>();
        map.put("token", Jwt);
//        5、系统用户相关的所有信息放入redis
        redisCache.setCacheObject("login:"+userId,userLogin);
        return new ResponseResult(200,"登陆成功",map);
    }

    @Override
    public ResponseResult loginOut() {//退出登录实现
//        退出登录只需要删除redis中的信息即可
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserLogin userLogin = (UserLogin) authentication.getPrincipal();
        Long id = userLogin.getUser().getId();
        redisCache.deleteObject("login:"+id);
        return new ResponseResult(200,"退出成功！");
    }
}
